<template>
  <a-modal
    :title="title"
    :width="800"
    :ok="false"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="机构名称"
          prop="departName"
          :hidden="false"
          hasFeedback
        >
          <a-input id="departName" placeholder="请输入机构/部门名称" v-model="model.departName" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :hidden="seen" label="上级部门" hasFeedback>
          <a-tree-select
            style="width: 100%"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="departTree"
            v-model="model.parentId"
            placeholder="请选择上级部门"
            :disabled="condition"
          >
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="机构类型">
          <template v-if="seen">
            <a-radio-group v-model="model.orgCategory" placeholder="请选择机构类型">
              <a-radio value="1"> 公司 </a-radio>
            </a-radio-group>
          </template>
          <template v-else>
            <a-radio-group v-model="model.orgCategory" placeholder="请选择机构类型">
              <a-radio value="2"> 区域 </a-radio>
              <a-radio value="3"> 机构 </a-radio>
            </a-radio-group>
          </template>
        </a-form-model-item>
        <a-form-model-item prop="description" :labelCol="labelCol" :wrapperCol="wrapperCol" label="区域编码">
          <a-input v-model="model.description"></a-input>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="部门负责人">
          <j-select-multi-user v-model="model.directorUserIds" valueKey="id"></j-select-multi-user>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="人口数">
          <a-input placeholder="请输入人口数" v-model="model.permanentPopulation" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="经度">
          <a-input placeholder="请输入经度" v-model="model.longitude" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="纬度">
          <a-input placeholder="请输入纬度" v-model="model.latitude" />
        </a-form-model-item>
        <div id="amap2"></div>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mobile" label="电话">
          <a-input placeholder="请输入电话" v-model="model.mobile" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="传真">
          <a-input placeholder="请输入传真" v-model="model.fax" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="地址">
          <a-input placeholder="请输入地址" v-model="model.address" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input-number v-model="model.departOrder" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-textarea placeholder="请输入备注" v-model="model.memo" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: 'ecb9d215b9a5feeac1ea044eeb9198f4',
}
import { httpAction } from '@/api/manage'
import { queryIdTree } from '@/api/api'
import pick from 'lodash.pick'
import ATextarea from 'ant-design-vue/es/input/TextArea'
export default {
  name: 'SysDepartModal',
  components: { ATextarea },
  data() {
    return {
      map: null,
      departTree: [],
      orgTypeData: [],
      phoneWarning: '',
      departName: '',
      title: '操作',
      seen: false,
      visible: false,
      condition: true,
      disableSubmit: false,
      model: {},
      defaultModel: {
        departOrder: 0,
        orgCategory: '1',
        longitude: null,
        latitude: null,
      },
      menuhidden: false,
      menuusing: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        departName: [{ required: true, message: '请输入机构/部门名称!' }],
        description: [{ required: true, message: '请输入区域编号!' }],
        mobile: [{ validator: this.validateMobile }],
        areaName: [{ required: true, message: '请输入机构类型!' }],
      },
      url: {
        add: '/sys/sysDepart/add',
      },
      dictDisabled: true,
    }
  },
  mounted() {},
  methods: {
    initMap(lnglat) {
      if (!lnglat || !lnglat.length) {
        return
      }
      AMapLoader.load({
        key: '7bf1afe0a111e75bc96b5f5d0553b5f3', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          // 是否加载 AMapUI，缺省不加载
          version: '1.1', // AMapUI 缺省 1.1
          plugins: [], // 需要加载的 AMapUI ui插件
        },
      })
        .then((AMap) => {
          AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
            this.map = new AMap.Map('amap2', {
              zoom: 16, //设置地图的缩放级别
              center: lnglat, //初始化地图中心点位置
            })
            const positionPicker = new PositionPicker({
              mode: 'dragMarker', //设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
              map: this.map, //依赖地图对象
            })
            // TODO:事件绑定、结果处理等
            positionPicker.on('success', (positionResult) => {
              console.log('positionResult', positionResult)
              if (positionResult.position.lng && positionResult.position.lat) {
                this.model.longitude = positionResult.position.lng
                this.model.latitude = positionResult.position.lat
                this.$forceUpdate()
              }
            })
            positionPicker.on('fail', (positionResult) => {
              // console.log('positionResult', positionResult)
              this.model.longitude = ''
              this.model.latitude = ''
              this.$forceUpdate()
            })
            positionPicker.start()
            // 任意点击地图某一点可以拿到经纬度
            this.map.on('click', (e) => {
              // console.log(e)
              console.log(e.lnglat.lng + ',', e.lnglat.lat)
              if (e.lnglat.lng && e.lnglat.lat) {
                positionPicker.stop()
                this.model.longitude = e.lnglat.lng
                this.model.latitude = e.lnglat.lat
                this.map.setCenter([e.lnglat.lng, e.lnglat.lat])
                setTimeout(() => {
                  positionPicker.start()
                }, 800)
              }
            })
          })
        })
        .catch((e) => {
          console.log(e)
        })
    },
    loadTreeData() {
      var that = this
      queryIdTree().then((res) => {
        if (res.success) {
          that.departTree = []
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.departTree.push(temp)
          }
        }
      })
    },
    add(depart) {
      if (depart) {
        this.seen = false
        this.dictDisabled = false
      } else {
        this.seen = true
        this.dictDisabled = true
      }
      this.edit(depart)
    },
    edit(record) {
      record = record || {}
      // console.log('record', record)
      this.visible = true
      this.model = Object.assign({}, this.defaultModel, record)
      this.loadTreeData()
      this.model.parentId = record != null ? record.toString() : null
      if (this.seen) {
        this.model.orgCategory = '1'
      } else {
        this.model.orgCategory = '2'
      }
      let lnglat = [record.longitude, record.latitude]
      if (!(record.latitude && record.longitude)) {
        lnglat = [119.646354, 29.129608]
      }
      // console.log('lnglat', lnglat)
      this.initMap(lnglat)
    },
    close() {
      this.$emit('close')
      this.disableSubmit = false
      this.visible = false
      this.$refs.form.resetFields()
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          httpAction(this.url.add, this.model, 'post')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadTreeData()
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }
    },
  },
}
</script>

<style scoped>
#amap2 {
  width: 505px;
  height: 330px;
  margin-left: 150px;
  margin-bottom: 20px;
}
</style>
